<template>
	<view class="_abbr">
		<view class="public">
			<view class="detail">
				<view class="main_body_view main_body_view_title">
					<u-row>
						{{dataForm.orderId}}
					</u-row>
				</view>
				<view class="main_body_view main_body_view_view">
					销毁单标题：{{dataForm.orderTitle || ''}}
				</view>
				<view class="main_body_view main_body_view_view">
					销毁单要求：{{dataForm.orderQuest || ''}}
				</view>
				<view class="main_body_view">
					销毁者：{{dataForm.destroyedUserName || ''}}
				</view>
				<view class="main_body_view">
					备注：{{dataForm.remark ||''}}
				</view>
			</view>
		</view>
		<view class="public">
			<u-tabs :current="dissCurrent" :is-scroll="false" @change="tabChange" :list="tabsList">
			</u-tabs>
			<view v-if="dissCurrent === 0">
				<u-form :model="detailForm">
					<u-form-item prop="deviceDiskQr">
						<view class="scan-item item1">
							<input
								:focus="isFocus" 
								placeholder="扫描或输入硬盘二维码" 
								:value="detailForm.deviceDiskQr"
								@blur="confirmDeviceDiskQr"
								type="text" 
								class="input">
							<view class="right-icon">
								<view class="icon" @click="doScanDeviceDiskQr">
									<u-icon size="30" name="scan"></u-icon>
								</view>
							</view>
						</view>
					</u-form-item>
					<u-form-item prop="deviceDiskSn">
						<view class="scan-item item1">
							<input
								:focus="isFocus" 
								placeholder="扫描或输入硬盘序列号" 
								:value="detailForm.deviceDiskSn"
								@blur="confirm1" 
								type="text" 
								class="input">
							<view class="right-icon">
								<view class="icon" @click="doScan1">
									<u-icon size="30" name="scan"></u-icon>
								</view>
							</view>
						</view>
					</u-form-item>
					<u-form-item prop="diskModel">
						<view class="scan-item item1" style="margin-top: 10px;">
							<u-input 
								v-model="detailForm.diskModel" 
								@tap="handleSelectDevice" 
								placeholder="选择硬盘型号" 
								border="false" 
								:show-action="false"
								>
							</u-input>
						</view>
					</u-form-item>
					<u-form-item>
						<view>数据销毁照片</view>
						<view>
							<u-upload 
								:fileList="fileList1" 
								@afterRead="afterRead" 
								@delete="deletePic" 
								name="1" 
								:maxCount="1">
							</u-upload>
						</view>
					</u-form-item>
				</u-form>
			</view>
			<view v-if="dissCurrent === 1">
				<u-form :model="detailForm">
					<u-form-item prop="deviceQr">
						<view class="scan-item item1" style="margin-bottom: -18px">
							<input
								:focus="isFocus" 
								placeholder="扫描或输入二维码" 
								:value="detailForm.deviceQr"
								@blur="confirmDeviceQr" 
								type="text" 
								class="input">
							<view class="right-icon">
								<view class="icon" @click="doScanDeviceQr">
									<u-icon size="30" name="scan"></u-icon>
								</view>
							</view>
						</view>
					</u-form-item>
					<u-form-item>
						<view class="content">
							<view v-for="item in detailForm.deviceModelMediaVos" :key="item.mediaId">
								<u-image 
									:showLoading="true" 
									:src="item.fileUrl" 
									width="100px"
									height="100px"
									>
								</u-image>
							</view>
							<view class="device">
								<view>
									{{ detailForm.deviceType || ''}} {{ detailForm.deviceBrand || ''}} {{detailForm.deviceModel || ''}}
								</view>
								<view>
									{{deviceSpecsNew || ''}}
								</view>
							</view>
						</view>
					</u-form-item>
					<u-form-item prop="deviceSn">
						<u-input
							v-model="detailForm.deviceSn"
							placeholder="设备序列号"
							disabled
						></u-input>
					</u-form-item>
					<u-form-item prop="devicePn">
						<u-input
							v-model="detailForm.devicePn"
							placeholder="设备资产编号"
							disabled
						></u-input>
					</u-form-item>
					<u-form-item prop="deviceDiskSn">
						<view class="scan-item item1">
							<input
								:focus="isFocus" 
								placeholder="扫描或输入硬盘序列号" 
								:value="detailForm.deviceDiskSn"
								@blur="confirm1" 
								type="text" 
								class="input">
							<view class="right-icon">
								<view class="icon" @click="doScan1">
									<u-icon size="30" name="scan"></u-icon>
								</view>
							</view>
						</view>
					</u-form-item>
					<u-form-item prop="diskModel">
						<view class="scan-item item1" style="margin-top: 10px;">
							<u-input 
								v-model="detailForm.diskModel" 
								@tap="handleSelectDevice" 
								placeholder="选择硬盘型号" 
								border="false" 
								:show-action="false"
								>
							</u-input>
						</view>
					</u-form-item>
					<u-form-item>
						<!-- <view>数据销毁前照片</view>
						<view>
							<u-upload 
								:fileList="fileList2" 
								@afterRead="afterRead" 
								@delete="deletePic" 
								name="2" 
								:maxCount="1">
							</u-upload>
						</view> -->
						<view>数据销毁照片</view>
						<view>
							<u-upload 
								:fileList="fileList1" 
								@afterRead="afterRead" 
								@delete="deletePic" 
								name="1" 
								:maxCount="1">
							</u-upload>
						</view>
					</u-form-item>
				</u-form>
			</view>
		</view>
		<view class="public">
			<view class="button">
				<u-button type="primary" @click="addDestroyDevice" text="提交" :disabled="buttonDisabled"></u-button>
				<u-button type="primary" @click="sub" text="结束销毁" :disabled="buttonDisabled"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	export default {
		name: 'main',
		onLoad(options) {
			uni.showLoading({
				title: "正在加载中"
			})
			this.getData(options.workId);
			this.BaseUrl = getApp().globalData.baseURL;
			uni.hideLoading()
		},
		onUnload() {
			uni.$off('q-sign') //移除监听事件
		},
		data() {
			return {
				tabsList: [
					{
						name: '拆卸销毁',
					},
					{
						name: '本机销毁',
					}
				], // tabs列表
				deviceFit: {},
				dissCurrent: 0,
				deviceSpecsNew: '',
				isFocus: true, // 二维码是否聚焦
				detailForm: {
					deviceQr: '',
					deviceDiskQr: '',
					deviceDiskSn: ''
				}, // 设备详情
				buttonDisabled: false,
				BaseUrl: "",
				dataForm: {}, // 数据工单
				historyList: [], //过程工单
				subForm: {
					orderId: null,
					method: "",
					testRemark: null
				}, //提交工单
				WorkOrderMediaBo: [], //工单文件
				fileList2: [],
				fileList1: [], //数据销毁照片
				deviceImages: {
					deviceQr: '',
					mediaType: "2002",
					mediaName: '数据销毁照片',
					fileUrls: []
				},
				deviceFrontImages: {
					deviceQr: '',
					mediaType: "2001",
					mediaName: '数据销毁前照片',
					fileUrls: []
				}
			}
		},
		methods: {
			// 拆卸销毁、本机销毁
			tabChange(item) {
				// console.log(index)
				this.dissCurrent = item.index
			},
			// 获取选择设备返回的参数
			otherFun(item) {
				if (item) {
					this.deviceFit = item
					this.detailForm.diskModel = this.deviceFit.deviceModel;
				}
			},
			// 跳转选取设备
			handleSelectDevice(index) {
				const workId = this.dataForm.orderId
				uni.navigateTo({
					url: 'deviceFit?workId=' + workId
				});
			},
			// 扫码二维码
			doScanDeviceDiskQr() {
				uni.scanCode({
					success: (res) =>{
						this.detailForm.deviceDiskQr = res.result
						this.getDeviceData1()
						// console.log(res.result)
					}
				})
			},
			doScanDeviceQr() {
				uni.scanCode({
					success: (res) =>{
						this.detailForm.deviceQr = res.result
						this.getDeviceData()
					}
				})
			},
			// 硬盘序列号
			doScan1() {
				uni.scanCode({
					success: (res) =>{
						this.detailForm.deviceDiskSn = res.result
						 this.$forceUpdate(); 
					}
				})
			},
			// 二维码确定
			confirm1(e) {
				this.isFocus = false
				this.detailForm.deviceDiskSn = e.detail.value
			},
			confirmDeviceDiskQr(e) {
				this.isFocus = false
				if (e.detail.value) {
					this.detailForm.deviceDiskQr = e.detail.value
					this.getDeviceData1()
				}
			},
			confirmDeviceQr(e) {
				this.isFocus = false
				if (e.detail.value) {
					this.detailForm.deviceQr = e.detail.value
					this.getDeviceData()
				}
			},
			// 提交工单
			sub() {
				let d = {}
				d.orderId = this.dataForm.orderId
				d.method = "destroyed_end"
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定结束销毁吗',
					success: function (res) {
						if (res.confirm) {
							// 提交
							request({
								url: 'system/destroyed',
								method: "PUT",
								data: d
							}).then(res => {
								uni.reLaunch({
									url: '/pages/view/destroy/index'
								})
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 新增设备
			addDestroyDevice(){
				// 设备照片
				this.deviceImages.deviceQr = this.detailForm.deviceQr
				// this.deviceFrontImages.deviceQr = this.detailForm.deviceQr
				this.detailForm.orderId = this.dataForm.orderId
				// this.detailForm.deviceQr = "CINO-R-q1"
				if (!this.detailForm.deviceDiskSn) {
					uni.showToast({
						title:"硬盘sn不能为空",
						icon:'none'
					})
					return
				}
				if (!this.detailForm.diskModel) {
					uni.showToast({
						title:"硬盘型号不能为空",
						icon:'none'
					})
					return
				}
				if (this.fileList1.length=== 0) {
					uni.showToast({
						title:"销毁照片未上传",
						icon:'none'
					})
					return
				}
				// this.detailForm.beforeDeviceDiskMediaUrl = this.fileList2[0].url
				this.detailForm.deviceDiskMediaUrl = this.fileList1[0].url
				if (this.detailForm.deviceModelMediaVos.length > 0) {
					this.detailForm.deviceMediaUrl = this.detailForm.deviceModelMediaVos[0].fileUrl
				}
				
				// 新增设备
				request({
					url: "system/destroyedDetail",
					method:"POST",
					data: this.detailForm
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title:"新增成功",
							icon:'none'
						})
						this.reset()
					} else if (res.code === 500) {
						uni.showToast({
							title:`${res.msg}`,
							icon:'none'
						})
						this.reset()
					}
				})
			},
			reset() {
				this.detailForm = {
					deviceQr: '',
					deviceSn: '',
					deviceDiskSn: ''
				}
				this.deviceImages = {
		 			deviceQr: '',
		 			mediaType: "2002",
		 			mediaName: '数据销毁照片',
		 			fileUrls: []
		 		}
				this.fileList1 = []
				this.deviceSpecsNew = ''
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.forEach((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
						params: {},
						/* 会加在url上 */
						// #ifdef APP-PLUS || H5
						files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
						// #endif
						filePath: url, // 要上传文件资源的路径。
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: {
							auth: true
						}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
						// #ifdef H5 || APP-PLUS
						timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
						// #endif
						header: {
							Authorization: uni.getStorageSync("token")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						formData: {}, // HTTP 请求中其他额外的 form data
						// 返回当前请求的task, options。请勿在此处修改options。非必填
						getTask: (task, options) => {},
					}).then((res) => {
						if (name == 1) {
							this.deviceImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						} 
						this.detailForm.deviceDiskMediaUrl = res.data.data.url.replace("blob:", ""),
						resolve(res.data.data.url)
						// 返回的res.data 已经进行JSON.parse
					}).catch(err => {

					})
				})
			},
			// 请求数据
			getData(workId) {
				request({
					method: "GET",
					url: `system/destroyed/${workId}`
				}).then(res => {
					this.dataForm = res.data;
					this.subForm.orderId = res.data.orderId;
				})
			},
			getDeviceData1() {
				if (this.detailForm.deviceQr.startsWith('CINO-R') || this.detailForm.deviceDiskQr.startsWith('CINO-R')) {
					request({
						method: "GET",
						url: `system/detail/${this.detailForm.deviceDiskQr}`,
					}).then(res => {
						if (res.data) {
							if (res.data.workOrderId !== this.dataForm.workOrderId) {
								uni.showToast({
									title:"请扫描该单的设备",
									icon:'none'
								})
								return
							}
						this.detailForm.deviceDiskQr = res.data.deviceQr
						this.detailForm.deviceDiskSn = res.data.deviceSn ||''
						this.detailForm.diskModel = res.data.deviceModel
						this.detailForm.deviceModelMediaVos = res.data.deviceModelMediaVos
						this.detailForm.deviceQr = res.data.ffDeviceQr
							
						} else {
							uni.showToast({
								title:"该设备不存在",
								icon:'none'
							})
						}
					})
				} else {
					uni.showToast({
						title:"设备二维码不符合要求",
						icon:'none'
					})
				}
			},
			// 获取单个设备详情
			getDeviceData() {
				if (this.detailForm.deviceQr.startsWith('CINO-R') || this.detailForm.deviceDiskQr.startsWith('CINO-R')) {
					request({
						method: "GET",
						url: `system/detail/${this.detailForm.deviceQr}`,
					}).then(res => {
						if (res.data) {
							if (res.data.workOrderId !== this.dataForm.workOrderId) {
								uni.showToast({
									title:"请扫描该单的设备",
									icon:'none'
								})
								return
							}
							this.detailForm = res.data
							// this.detailForm.diskModel = ''
							const specsArray = JSON.parse(res.data.deviceSpecs || "[]");
							this.deviceSpecsNew = specsArray.map(spec => spec[2]).join(' ');
						} else {
							uni.showToast({
								title:"该设备不存在",
								icon:'none'
							})
						}
					})
				} else {
					uni.showToast({
						title:"设备二维码不符合要求",
						icon:'none'
					})
				}
			},
			// 存储图片
			checkImages(imageForms) {
				for (let dataElement of imageForms) {
					switch (dataElement.mediaType) {
						case "1": 
							if (dataElement.fileUrl !== null) {
								this.fileList1.push({
									type: "image",
									url: dataElement.fileUrl,
									status: "success",
									name: "",
									message: "",
									thumb: "",
									size: 60489
								})
							}
						default:
							continue;
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		// position: absolute;
		background-color: rgba(244, 249, 254, 1);

		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);
			.main_body_view {
				margin: 10upx;
			}
			.device-border {
				border: 1px solid #eee; 
				border-radius: 3px; 
				padding: 4px;
				margin-bottom: 6px;
			}
			.back-icon {
			    background-color: black;
			    width: 24px;
			    height: 24px;
			    border-radius: 12px;
				position: relative;
			    margin: auto;
			    .add-icon {
					position: absolute;
					top: -1px;
					left: 7px;
			        color: #ffffff;
			        font-size: 18px;
			        line-height: 24px; /* 让文本垂直居中 */
					text-align: center; /* 让文本水平居中 */
			    }
			}
			.button {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
			.main_body_view_title {
				border-bottom: 1px solid black;
				margin-bottom: 10upx;
			}
			.total-count {
				display: flex;
				align-items: center;
				justify-content: center; 
				margin-top: 10px; 
				font-size: 16px;
			}
			.scan-item {
				// margin-top: 10px;
				.input {
					margin: 10px 0 10px 6px;
					width: 100%;
				}
				.right-icon {
					position: relative;
					box-sizing: border-box;
					position: sticky;
					top: 0;
					z-index: 999;
					display: flex;
					overflow: hidden;
					justify-content: space-around;
					background: rgb(255, 255, 255);
					margin: 6px;
					.scan {
						position: absolute;
						top: 10upx;
						right:14upx;
					}
				}
				.device {
					display: flex;
					margin: 10px 0;
					justify-content: space-between;
				}
				.device-item {
					display: flex;
					align-items: center;
					flex-direction: column;
				}
				.test-scan {
					border: 1px solid #eee;
					padding: 8px;
				}
				.button {
					text-align: center; 
					margin-top: 40rpx;
					display: flex;
				}
			}
			.content {
				display: flex; 
				align-items: center; 
				justify-content: center;
				.device {
					// text-align: center; 
					flex: 1; 
					margin-left: 10px;
					font-size: 14px;
				}
			}
			.item1 {
				display: flex; 
				border: 1px solid #eee;
			}
			.user_for {
				display: flex;
			}
			.line_for {
				width: 4rpx;
				height: 24rpx;
				margin: 0 20rpx 10rpx;
			}
			.line_radio {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				position: relative;
				left: 50%;
				transform: translateX(-50%);
				top: 0;
			}
			.right_box {
				padding: 0rpx 20rpx 20rpx 20rpx;
			}
			.desc {
				font-size: 30rpx;
				display: flex;
				margin-top: 20rpx;
				align-items: center;
			}
		}
		.write {
			display: flex;
			justify-content: space-around;
			.im {
				width: 300rpx;
				image {
					width: 200rpx;
					height: 300rpx;
					position: relative;
					left: 30rpx;
				}
			}
		}
	}
</style>